from rest_framework import generics, status, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from .models import Comment, CommentReply, CommentReport
from .serializers import (
    CommentListSerializer, CommentCreateSerializer,
    CommentAdminSerializer, CommentReportSerializer,
    CommentReportAdminSerializer, CommentVoteSerializer
)
from .filters import CommentFilter


class CommentListView(generics.ListAPIView):
    serializer_class = CommentListSerializer
    permission_classes = [permissions.AllowAny]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = CommentFilter
    ordering_fields = ['created_at', 'rating', 'helpful_count']
    ordering = ['-created_at']
    
    def get_queryset(self):
        book_id = self.kwargs.get('book_id')
        if book_id:
            return Comment.objects.filter(
                book_id=book_id,
                is_approved=True
            ).select_related('user', 'book')
        return Comment.objects.filter(is_approved=True)


class CommentCreateView(generics.CreateAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentCreateSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        book = serializer.validated_data['book']
        
        # 检查用户是否已经评论过这本书
        if Comment.objects.filter(book=book, user=request.user).exists():
            return Response(
                {'error': '您已经评论过这本书'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        comment = serializer.save(user=request.user)
        
        return Response(
            CommentListSerializer(comment).data,
            status=status.HTTP_201_CREATED
        )


class CommentDetailView(generics.RetrieveAPIView):
    queryset = Comment.objects.filter(is_approved=True)
    serializer_class = CommentListSerializer
    permission_classes = [permissions.AllowAny]


class CommentAdminListView(generics.ListAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentAdminSerializer
    permission_classes = [permissions.IsAdminUser]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = CommentFilter
    ordering_fields = ['created_at', 'rating', 'is_approved']
    ordering = ['-created_at']


class CommentAdminUpdateView(generics.UpdateAPIView):
    queryset = Comment.objects.all()
    serializer_class = CommentAdminSerializer
    permission_classes = [permissions.IsAdminUser]
    
    def patch(self, request, *args, **kwargs):
        comment = self.get_object()
        old_approved = comment.is_approved
        
        serializer = self.get_serializer(comment, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save(approved_by=request.user)
        
        # 如果评论被批准，发送通知
        if not old_approved and comment.is_approved:
            # 这里可以添加发送通知的逻辑
            pass
        
        return Response(serializer.data)


class CommentReportCreateView(generics.CreateAPIView):
    queryset = CommentReport.objects.all()
    serializer_class = CommentReportSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        comment = serializer.validated_data['comment']
        
        # 检查用户是否已经举报过这条评论
        if CommentReport.objects.filter(
            comment=comment, 
            reporter=request.user
        ).exists():
            return Response(
                {'error': '您已经举报过这条评论'},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        report = serializer.save(reporter=request.user)
        
        return Response(
            CommentReportSerializer(report).data,
            status=status.HTTP_201_CREATED
        )


class CommentReportListView(generics.ListAPIView):
    queryset = CommentReport.objects.all()
    serializer_class = CommentReportAdminSerializer
    permission_classes = [permissions.IsAdminUser]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    ordering_fields = ['created_at', 'status']
    ordering = ['-created_at']


class CommentReportUpdateView(generics.UpdateAPIView):
    queryset = CommentReport.objects.all()
    serializer_class = CommentReportAdminSerializer
    permission_classes = [permissions.IsAdminUser]
    
    def patch(self, request, *args, **kwargs):
        report = self.get_object()
        
        serializer = self.get_serializer(
            report, 
            data=request.data, 
            partial=True
        )
        serializer.is_valid(raise_exception=True)
        serializer.save(processed_by=request.user)
        
        return Response(serializer.data)


class CommentReplyCreateView(generics.CreateAPIView):
    queryset = CommentReply.objects.all()
    serializer_class = CommentReplySerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def create(self, request, *args, **kwargs):
        comment_id = self.kwargs['comment_id']
        
        try:
            comment = Comment.objects.get(id=comment_id)
        except Comment.DoesNotExist:
            return Response(
                {'error': '评论不存在'},
                status=status.HTTP_404_NOT_FOUND
            )
        
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        reply = serializer.save(
            user=request.user,
            comment=comment
        )
        
        return Response(
            CommentReplySerializer(reply).data,
            status=status.HTTP_201_CREATED
        )


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def comment_vote(request, comment_id):
    try:
        comment = Comment.objects.get(id=comment_id)
    except Comment.DoesNotExist:
        return Response(
            {'error': '评论不存在'},
            status=status.HTTP_404_NOT_FOUND
        )
    
    serializer = CommentVoteSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    
    vote_type = serializer.validated_data['vote_type']
    
    if vote_type == 'helpful':
        comment.helpful_count += 1
    elif vote_type == 'unhelpful':
        comment.unhelpful_count += 1
    
    comment.save()
    
    return Response({
        'helpful_count': comment.helpful_count,
        'unhelpful_count': comment.unhelpful_count
    })


@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def user_comments(request):
    comments = Comment.objects.filter(
        user=request.user
    ).select_related('book').order_by('-created_at')
    
    serializer = CommentListSerializer(comments, many=True)
    return Response(serializer.data)


@api_view(['GET'])
@permission_classes([permissions.IsAdminUser])
def comment_stats(request):
    from django.db.models import Count, Avg
    
    stats = {
        'total_comments': Comment.objects.count(),
        'approved_comments': Comment.objects.filter(is_approved=True).count(),
        'pending_comments': Comment.objects.filter(is_approved=False).count(),
        'total_reports': CommentReport.objects.count(),
        'pending_reports': CommentReport.objects.filter(status='pending').count(),
        'average_rating': Comment.objects.filter(is_approved=True).aggregate(
            avg=Avg('rating')
        )['avg'] or 0,
    }
    
    return Response(stats)
